package org.ocelot.tunes4j.gui;

import eu.medsea.mimeutil.MimeUtil;
import eu.medsea.mimeutil.detector.MagicMimeMimeDetector;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableRowSorter;

import org.ocelot.tunes4j.event.PlayerEvent;
import org.ocelot.tunes4j.event.PlayerEventListener;
import org.ocelot.tunes4j.player.JLayerPlayer;
import org.ocelot.tunes4j.utils.ResourceLoader;

import com.birosoft.liquid.LiquidLookAndFeel;
import com.explodingpixels.macwidgets.LabeledComponentGroup;
import com.explodingpixels.macwidgets.MacButtonFactory;
import com.explodingpixels.macwidgets.MacIcons;
import com.explodingpixels.macwidgets.MacWidgetFactory;
import com.explodingpixels.macwidgets.SourceList;
import com.explodingpixels.macwidgets.SourceListCategory;
import com.explodingpixels.macwidgets.SourceListControlBar;
import com.explodingpixels.macwidgets.SourceListItem;
import com.explodingpixels.macwidgets.SourceListModel;
import com.explodingpixels.macwidgets.SourceListSelectionListener;
import com.explodingpixels.macwidgets.UnifiedToolBar;
import com.explodingpixels.widgets.PopupMenuCustomizerUsingStrings;

public class WindowSample extends JFrame  {
	
	private static final long serialVersionUID = -7319833806607935833L;
    private UnifiedToolBar fUnifiedToolBar;
    private SourceList fSourceList;
	private JSplitPane splitPane;
	private MediaTable mediaTable;
	private JLayerPlayer player;
	private SourceListModel model = new SourceListModel();
	
	Icon musicPlaylistIcon 		= ResourceLoader.ICON_MUSIC;
	Icon moviesPlaylistIcon 	= ResourceLoader.ICON_MOVIES;
	Icon tvShowsPlaylistIcon 	= ResourceLoader.ICON_TVSHOWS;
	Icon podcastsPlaylistIcon 	= ResourceLoader.ICON_PODCASTS;
	Icon playlistIcon 			= ResourceLoader.ICON_PLAYLIST;
	Icon smartPlaylistIcon 		= ResourceLoader.ICON_SMARTPLAYLIST;
    Icon emuleIcon 				= ResourceLoader.ICON_EMULE;
    Icon aresIcon 				= ResourceLoader.ICON_ARES;
    
    SourceListCategory libraryCategory = new SourceListCategory("Library");
    SourceListCategory storeCategory = new SourceListCategory("Available NetWorks");
    SourceListCategory playlistCategory = new SourceListCategory("Playlists");

    
	public WindowSample() {
		
        fUnifiedToolBar = createUnifiedToolBar();
        fUnifiedToolBar.installWindowDraggerOnWindow(this);
        JSplitPane splitPane = createSourceList();
		setJMenuBar(getJMenuBar());
        add(fUnifiedToolBar.getComponent(), BorderLayout.NORTH);
        add(splitPane, BorderLayout.CENTER);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		setSize(800, 600);
		setLocationRelativeTo(null);
		setVisible(true); 
	}
	
	
	private UnifiedToolBar createUnifiedToolBar() {
        Icon blueGlobeIcon = new ImageIcon(DEverything.class.getResource(
                "/com/explodingpixels/macwidgets/icons/DotMac.png"));
        Icon greyGlobeIcon = new ImageIcon(DEverything.class.getResource(
                "/com/explodingpixels/macwidgets/icons/Network.png"));
        Icon preferences = new ImageIcon(DEverything.class.getResource(
                "/com/explodingpixels/macwidgets/icons/PreferencesGeneral.png"));
        Icon gear = new ImageIcon(DEverything.class.getResource(
                "/com/explodingpixels/macwidgets/icons/Advanced.png"));

        AbstractButton greyGlobeButton =
                MacButtonFactory.makeUnifiedToolBarButton(
                        new JButton("Network", greyGlobeIcon));
        greyGlobeButton.setEnabled(false);

        AbstractButton blueButton = new JButton("Media Cloud", blueGlobeIcon);
        blueButton.setEnabled(true);

        UnifiedToolBar toolBar = new UnifiedToolBar();
        toolBar.addComponentToLeft(MacButtonFactory.makeUnifiedToolBarButton(
                blueButton));
        toolBar.addComponentToLeft(greyGlobeButton);
        toolBar.addComponentToLeft(MacButtonFactory.makeUnifiedToolBarButton(
                new JButton("Preferences", preferences)));
        toolBar.addComponentToCenter(getPlayerPanel());
        toolBar.addComponentToRight(MacButtonFactory.makeUnifiedToolBarButton(
                new JButton("Advanced", gear)));
        
        final RoundField textField = new RoundField(10);
        textField.putClientProperty("JTextField.variant", "search");
        textField.addKeyListener(new KeyAdapter() {
        	@Override
        	public void keyPressed(KeyEvent e) {
				String text = textField.getText();
				TableRowSorter sorter = (TableRowSorter) mediaTable.getSorter();
				if (text.length() == 0) {
					sorter.setRowFilter(null);
				} else {
					sorter.setRowFilter(RowFilter.regexFilter(text));
				}
        	}
        } );
        
        
        
        toolBar.addComponentToRight(new LabeledComponentGroup("search", textField).getComponent());
        return toolBar;
    }
	
	public JLayerPlayer getPlayer() {
		return player;
	}
	
	 private JComponent getPlayerPanel() {

		    player = new JLayerPlayer();
			JPanel panel = new JPanel();
			JButton play = new JButton("Play");
			play.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					player.playback();
				}
			});
			final JButton pause = new JButton("Paused");
			pause.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					if (player.isPaused()) {
						pause.setText("Playing");
						player.resumePlayback();
					} else {
						pause.setText("Paused");
						player.pausePlayBack();
					}
				}
			});
			final JButton stop = new JButton("Stop");
			stop.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					player.stopPlaying();
				}
			});
			final JSlider slider = new JSlider();
			player.addMyEventListener(new PlayerEventListener() {
				@Override
				public void fireOnOpenEvent(PlayerEvent evt) {
					slider.setMaximum(player.getLength());
				}
			});
			player.addMyEventListener(new PlayerEventListener() {
				@Override
				public void fireOnPlayEvent(PlayerEvent evt) {
					slider.setValueIsAdjusting(true);
					slider.setValue(evt.getPropertyAsInt("song.bytelength"));
				}
			});
			
			slider.addChangeListener(new ChangeListener(){
				@Override
				public void stateChanged(ChangeEvent e) {
					if(!slider.getValueIsAdjusting()) {
						player.skipBytes(slider.getValue());
					}
				}
			});
			panel.setLayout(new FlowLayout());
			panel.add(play);
			panel.add(pause);
			panel.add(stop);
			panel.add(slider);
			return panel;
	 }


	public JSplitPane createSourceList() {
	        model.addCategory(libraryCategory);
	        model.addCategory(storeCategory);
	        model.addCategory(playlistCategory);
	        model.addItemToCategory(new SourceListItem("Music", musicPlaylistIcon), libraryCategory);
	        model.addItemToCategory(new SourceListItem("Movies", moviesPlaylistIcon), libraryCategory);
	        model.addItemToCategory(new SourceListItem("TV Shows", tvShowsPlaylistIcon), libraryCategory);
	        model.addItemToCategory(new SourceListItem("Podcasts", podcastsPlaylistIcon), libraryCategory);
	        model.addItemToCategory(new SourceListItem("eMule", emuleIcon), storeCategory);
	        model.addItemToCategory(new SourceListItem("Ares", aresIcon), storeCategory);
	        model.addItemToCategory(new SourceListItem("My playlist", playlistIcon), playlistCategory);
	        model.addItemToCategory(new SourceListItem("My smart playlist", smartPlaylistIcon), playlistCategory);
	        fSourceList = new SourceList(model);
	        fSourceList.addSourceListSelectionListener(new SourceListSelectionListener() {
				@Override
				public void sourceListItemSelected(SourceListItem item) {
					if(item==null) return;
					if(item.getText().equals("eMule")){ 
						TabbedPaneDemo panel = new TabbedPaneDemo();
						//DonkeyCore core = new DonkeyCore();
						//JPanel panel = new DonkeyGui(core);
						splitPane.setRightComponent(panel);
					}else if (item.getText().equals("Music")){
						splitPane.setRightComponent(getMediaTablePane());
					}else if (item.getIcon()==playlistIcon){
						splitPane.setRightComponent(getMediaTablePane());
					}
				}
	        });
	        SourceListControlBar controlBar = new SourceListControlBar();
	        controlBar.createAndAddButton(MacIcons.PLUS, new ActionListener() {
	            public void actionPerformed(ActionEvent e) {
	               // model.addItemToItem(new SourceListItem(("Hello")), itemG);
	            }
	        });
	        controlBar.createAndAddButton(MacIcons.MINUS, null);
	        controlBar.createAndAddPopdownButton(MacIcons.GEAR,
	                new PopupMenuCustomizerUsingStrings(null, "Item One", "Item Two", "Item Three"));
	        fSourceList.installSourceListControlBar(controlBar);
	        splitPane = MacWidgetFactory.createSplitPaneForSourceList(fSourceList, getMediaTablePane());
	        splitPane.setDividerLocation(200);
	        controlBar.installDraggableWidgetOnSplitPane(splitPane);
	        return splitPane;
	    }
	
    public  JScrollPane getMediaTablePane() {
    	return getMediaTable().getTablePane();
    }
	
    public  MediaTable getMediaTable() {
    	
    	if(mediaTable==null) { 
    		mediaTable = new MediaTable(this);
    	}
    	return mediaTable;
    
    }
    
    public JMenuBar getJMenuBar(){
    	JMenuBar menuBar = new JMenuBar();
    	JMenu fileMenu = new JMenu("File"); // Create File menu
    	JMenuItem importFolderItem = new JMenuItem("Import Folder ... ");
    	importFolderItem.addActionListener(new ActionListener(){
			@Override
    		public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
			    chooser.setCurrentDirectory(new java.io.File("."));
			    chooser.setDialogTitle("choosertitle");
			    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			    chooser.setAcceptAllFileFilterUsed(false);
			    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			    } else {
			      System.out.println("No Selection ");
			    }
			}
        });
    	
    	fileMenu.add(importFolderItem);
       	JMenuItem importFileItem = new JMenuItem("Add File(s) ...");
        fileMenu.add(importFileItem);
        fileMenu.add(new JSeparator());
    	JMenuItem newPlayListItem = new JMenuItem("New PlayList");
    	newPlayListItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
    	fileMenu.add(newPlayListItem);
        newPlayListItem.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				model.addItemToCategory(new SourceListItem("My playlist", playlistIcon), playlistCategory);
				
			}
        });
        
        JMenuItem newPlayListSelectItem = new JMenuItem("New PlayList From Selection");
        fileMenu.add(newPlayListSelectItem);
        JMenuItem newSmartPlayListItem = new JMenuItem("New SmartList PlayList");
        fileMenu.add(newSmartPlayListItem);
        fileMenu.add(new JSeparator());
        JMenuItem exitItem = new JMenuItem("Exit");
        fileMenu.add(exitItem);
        exitItem.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
        });
    	JMenu editMenu = new JMenu("Edit"); // Create Edit menu
    	editMenu.setMnemonic(KeyEvent.VK_E);
    	JMenuItem selectAllItem = new JMenuItem("Select All");
    	selectAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
    	selectAllItem.addActionListener(new ActionListener(){
 			@Override
 			public void actionPerformed(ActionEvent e) {
 					mediaTable.getTable().selectAll();
 			}
         });
    	JMenuItem deleteItem = new JMenuItem("Delete ");
    	deleteItem.setAccelerator(KeyStroke.getKeyStroke("DELETE"));
    	deleteItem.setMnemonic(KeyEvent.VK_D);
    	deleteItem.addActionListener(new ActionListener(){
 			@Override
 			public void actionPerformed(ActionEvent e) {
 				if(fSourceList.getSelectedItem()!=null && playlistCategory!=null)
 					fSourceList.getModel().removeItemFromCategory(fSourceList.getSelectedItem(), playlistCategory);
 				else
 					mediaTable.removeSelectedItems();
 			}
         });
    	
    	editMenu.add(selectAllItem);
    	editMenu.add(deleteItem);
    	menuBar.add(fileMenu); // Add the File menu
    	menuBar.add(editMenu); // Add the edit menu
        return menuBar;
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
    	//	JFrame.setDefaultLookAndFeelDecorated(true); //que nos permite dejar a Substance la decoracion ( por asi decirlo)
		//	SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.NebulaSkin"); // Setencia que aplica el skin Creme de Substance
//		
    	LiquidLookAndFeel.setLiquidDecorations(true,"mac");
    	UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
    	MimeUtil.addMimeDetector(new MagicMimeMimeDetector()); // Inicializa MimeDetector;
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					new WindowSample();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}
